package me.qingy.programmatic;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

/**
 * 数值转字符串及字符串转数值
 *
 * @author qingy
 * @since 2021/8/19
 */
public class PalindromeNumber {

    /**
     * int => String => int 数值转字符串，字符串再转数值
     * return originalInt == reversedInt
     */
    public boolean isPalindrome1(int x) {
        if (x < 0) return false;

        int backup = x;
        long y = 0; // long 防止溢出
        while (x != 0){
            y = y * 10 + x % 10;
            x = x / 10;
        }
        return y == backup;
    }

    /**
     * 融入题解 toString
     * -2147483647 ~ 2147483647
     */
    public boolean isPalindrome2(int x) {
        if (x < 0) return false;

        int[] digits = new int[10];
        int k = 0;
        while (x != 0) {
            digits[k] = x % 10;
            x = x / 10;
            k++;
        }

        for (int i = 0; i < k / 2; i++) {
            if (digits[i] != digits[k - 1 - i]) { // k-- = k - i++
                return false;
            }
        }
        return true;
    }

    /**
     * 通用 toString
     */
    public boolean isPalindrome3(int x) {
        String s = toString(x);
        char[] chars = s.toCharArray();

        int k = chars.length - 1;
        for (int i = 0; i < chars.length / 2; i++) {
            if (chars[i] != chars[k]) {
                return false;
            }
            k--;
        }
        return true;
    }

    public String toString(int x) {
        boolean negative = x < 0;
        if (negative) {
            x = x * -1;
        }
        StringBuilder sb = new StringBuilder();
        if (x == 0) {
            sb.append(0);
        }
        while (x != 0) { // 主要知晓数值转字符串原理
            sb.append(x % 10);
            x = x / 10;
        }
        if (negative) {
            sb.append("-");
        }
        return sb.reverse().toString();
    }

    @Test
    public void testIsPalindrome() {
        Assertions.assertTrue(isPalindrome1(1001));
        Assertions.assertTrue(isPalindrome1(121));
        Assertions.assertFalse(isPalindrome1(-121));
        Assertions.assertFalse(isPalindrome1(10));
        Assertions.assertFalse(isPalindrome1(-101));

        Assertions.assertEquals("123456789", toString(123456789));
        Assertions.assertEquals("-123456789", toString(-123456789));
        Assertions.assertEquals("0", toString(0));
    }
}
